import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/router/page_router.dart';
import 'package:yqmssa_app/utils/shared_utils.dart';
import 'package:yqmssa_app/utils/tencent_im_utils.dart';
import 'package:yqmssa_app/views/index/request/index_request.dart';
import 'package:yqmssa_app/views/landing/apply_request.dart';
import 'package:yqmssa_app/views/message/chat_method.dart';

import 'message_manager.dart';

class HomeSheetScreen extends StatefulWidget {
  final int id;
  const HomeSheetScreen({super.key, required this.id});

  @override
  State<HomeSheetScreen> createState() => _HomeSheetScreenState();
}

class _HomeSheetScreenState extends State<HomeSheetScreen> {
  final data = VideoDetailDataModel().obs;

  final queryData = Get.parameters;

  late CreateApplyDataModel applyDataModel;

  final range = ["1-5万", "5-20万", "20-30万", "30-80万", "80万以上"];

  final rangeType = ["信用卡", "网贷", "企业贷", "信用贷", "其他"];

  final selRange = [].obs;

  final selRangeType = [].obs;

  void gD() {
    ApplyRequest.getVI(widget.id).then((value) {
      data.value = value;
    });
  }

  void gQ() {
    ApplyRequest.getQuestion().then((value) {
      // data.value.question = value;
    });
  }

  void select({
    int type = 0,
    String value = "",
  }) {
    if (type == 0) {
      if (selRange.contains(value)) {
        selRange.remove(value);
      } else {
        selRange.add(value);
      }
    }
    if (type == 1) {
      if (selRangeType.contains(value)) {
        selRangeType.remove(value);
      } else {
        selRangeType.add(value);
      }
    }
  }

  ///提交线索
  void putApply() {
    if (selRangeType.isEmpty) {
      SmartDialog.showToast("请选择债务类型");
      return;
    }
    if (selRange.isEmpty) {
      SmartDialog.showToast("请选择债务总金额");
      return;
    }
    final parameters = {
      'video_id': data.value.video?.id ?? 0,
      'debt_range': selRangeType.join(","),
      'money_range': selRange.join(","),
      "overdue_duration": "",
      "username": "",
      "other_touch": "",
      "mobile_time": "",
      "admin_last_id": data.value.adminId
    };
    SmartDialog.showLoading(msg: "正在提交申请");
    ApplyRequest.plan(parameters).then((value) async {
      applyDataModel = value;
      sharedUtils.service = value;
      sendIm();
      SmartDialog.dismiss();
      SmartDialog.showToast("已收到你的申请，稍后会有法务专员联系您");
      gotoChat();
    }).catchError((err) {
      SmartDialog.dismiss();
      SmartDialog.showToast(err.message ?? "");
      gD();
    });
  }

  ///发送第一条Im信息
  void sendIm() {
    ChatMethods.sendMessage(AppConfig.appInitData.chatBot == 1 ? "@customer_service_account" : applyDataModel.serviceTencentId);
  }

  ///跳转微信并且跳转聊天
  void gotoChat() {
    Get.back();
    tencentImUtils.pushPage();
    Get.find<MessageManager>().getSystemMsg();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 24),
      decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(left: 4),
            child: RichText(
              text: const TextSpan(style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), children: [
                TextSpan(
                  text: "您的逾期平台类型",
                  style: TextStyle(color: Color(0XFF333333)),
                ),
                TextSpan(
                  text: "*",
                  style: TextStyle(color: Color(0XFFFF3F3F)),
                ),
              ]),
            ),
          ),
          const SizedBox(height: 16),
          GridView.builder(
            itemCount: rangeType.length,
            shrinkWrap: true,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 4,
              mainAxisSpacing: 16,
              crossAxisSpacing: 24,
            ),
            itemBuilder: (context, index) {
              return InkWell(
                onTap: () {
                  select(type: 1, value: rangeType[index]);
                },
                child: Obx(() {
                  return Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: selRangeType.contains(rangeType[index]) ? const Color(0XFFFF6800) : null,
                      borderRadius: BorderRadius.circular(4),
                      boxShadow: selRangeType.contains(rangeType[index])
                          ? [BoxShadow(color: const Color(0XFFFF6800).withOpacity(0.25), blurRadius: 8, offset: const Offset(0, 4))]
                          : null,
                      border: Border.all(width: 1, color: const Color(0XFFD9D9D9)),
                    ),
                    child: Text(
                      rangeType[index],
                      style: TextStyle(color: selRangeType.contains(rangeType[index]) ? Colors.white : Colors.black),
                    ),
                  );
                }),
              );
            },
          ),
          const SizedBox(height: 16),
          Padding(
            padding: const EdgeInsets.only(left: 4),
            child: RichText(
              text: const TextSpan(style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), children: [
                TextSpan(
                  text: "您的债务逾期金额",
                  style: TextStyle(color: Color(0XFF333333)),
                ),
                TextSpan(
                  text: "*",
                  style: TextStyle(color: Color(0XFFFF3F3F)),
                ),
              ]),
            ),
          ),
          const SizedBox(height: 16),
          GridView.builder(
            itemCount: range.length,
            shrinkWrap: true,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 4,
              mainAxisSpacing: 16,
              crossAxisSpacing: 24,
            ),
            itemBuilder: (context, index) {
              return InkWell(
                onTap: () {
                  select(type: 0, value: range[index]);
                },
                child: Obx(() {
                  return Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: selRange.contains(range[index]) ? const Color(0XFFFF6800) : null,
                      borderRadius: BorderRadius.circular(4),
                      boxShadow: selRange.contains(range[index])
                          ? [BoxShadow(color: const Color(0XFFFF6800).withOpacity(0.25), blurRadius: 8, offset: const Offset(0, 4))]
                          : null,
                      border: Border.all(width: 1, color: const Color(0XFFD9D9D9)),
                    ),
                    child: Text(
                      range[index],
                      style: TextStyle(color: selRange.contains(range[index]) ? Colors.white : Colors.black),
                    ),
                  );
                }),
              );
            },
          ),
          const SizedBox(height: 32),
          GestureDetector(
            onTap: putApply,
            child: Container(
              height: 44,
              decoration: BoxDecoration(
                color: const Color(0XFFFF6800),
                borderRadius: BorderRadius.circular(4),
                boxShadow: [BoxShadow(color: const Color(0XFFFF6800).withOpacity(0.25), blurRadius: 8, offset: const Offset(0, 4))],
              ),
              alignment: Alignment.center,
              child: Text(
                (AppConfig.appInitData.channelText?.submitText ?? "").isEmpty ? "立即提交处理" : AppConfig.appInitData.channelText?.submitText ?? "",
                style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Colors.white, height: 1),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          const SizedBox(height: 16),
          Center(
            child: RichText(
              textAlign: TextAlign.center,
              text: TextSpan(style: const TextStyle(color: Color(0XFF666666)), children: [
                TextSpan(text: data.value.fullName),
                WidgetSpan(
                    child: InkWell(
                  onTap: () {
                    Get.toNamed(PageRouter.infoState, parameters: {"html": data.value.statementContent});
                  },
                  child: Text(
                    data.value.statementTitle,
                    style: const TextStyle(color: Color(0XFFF18883)),
                  ),
                )),
              ]),
            ),
          ),
        ],
      ),
    );
  }
}
